package com.icss.ah.base.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * 数据库连接
 * 
 */
public class DBUtil {
	public static Map hm = Collections.synchronizedMap(new HashMap());
	public final static String ETMP = "java:comp/env/jdbc/etmp";
	/**
	 * 获取数据库连接
	 * @param dataSourceName
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection(String dataSourceName)throws SQLException {
		Context ctx = null;
		Connection conn = null;
		DataSource ds = (DataSource) DBUtil.hm.get(dataSourceName);
		if (ds == null) {
			try {
				ctx = new InitialContext();
				ds = (DataSource) ctx.lookup(dataSourceName);
				DBUtil.hm.put(dataSourceName, ds);
			} catch (NamingException e) {
				e.printStackTrace();
			} finally {
				try {
					if (ctx != null)
						ctx.close();
				} catch (NamingException e) {
					e.printStackTrace();
				}
			}
		}
		if (ds != null)
			conn = ds.getConnection();
		if (conn != null)
			conn.setAutoCommit(true);
		return conn;
	}

	/**
	 * 关闭ResultSet
	 * @param ResultSet
	 * @return
	 * @throws SQLException
	 */
	public static void close(ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 关闭Statement
	 * @param Statement
	 * @return
	 * @throws SQLException
	 */
	public static void close(Statement stmt) {
		try {
			if (stmt != null)
				stmt.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}
	/**
	 * 关闭Connection
	 * @param Connection
	 * @return
	 * @throws SQLException
	 */
	public static void close(Connection conn) {
		try {
			if (conn != null && !conn.isClosed()) {
				if (!conn.getAutoCommit()) {
					conn.rollback();
					conn.setAutoCommit(true);
				}
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}